//判断运行环境 windows还是android
var IS_ANDROID = navigator.userAgent.toLowerCase().indexOf("android") > 0 ? true : false;
var MODEL = "PUBLISH"; //判断是预览还是发布
var INIT = true;
var MUTED = false;//静音
var iframe = "";
var iframe_src = "";
var STOP = false;
/**随机生成timer **/
function randomString(length) {
  var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var result = '';
  for (var i = length; i > 0; --i)
    result += str[Math.floor(Math.random() * str.length)];
  return result;
}

/**时间控件**/
function tick() {
  var hours, minutes, seconds, xfile;
  var intHours, intMinutes, intSeconds;
  var today, theday;
  today = new Date();
  function initArray() {
    this.length = initArray.arguments.length
    for (var i = 0; i < this.length; i++)
      this[i + 1] = initArray.arguments[i]
  }
  var d = new initArray("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
  theday = today.getFullYear() + "年" + [today.getMonth() + 1] + "月" + today.getDate() + d[today.getDay() + 1];
  intHours = today.getHours();
  intMinutes = today.getMinutes();
  intSeconds = today.getSeconds();
  if (intHours == 0) {
    hours = "12:";
    xfile = "午夜";
  } else if (intHours < 12) {
    hours = intHours + ":";
    xfile = "上午";
  } else if (intHours == 12) {
    hours = "12:";
    xfile = "正午";
  } else {
    intHours = intHours - 12
    hours = intHours + ":";
    xfile = "下午";
  }
  if (intMinutes < 10) {
    minutes = "0" + intMinutes + ":";
  } else {
    minutes = intMinutes + ":";
  }
  if (intSeconds < 10) {
    seconds = "0" + intSeconds + " ";
  } else {
    seconds = intSeconds + " ";
  }
  timeString = theday + xfile + hours + minutes + seconds;
  $('foreignObject[tag="time"] .time').css("position", "relative").html(timeString);
  window.setTimeout("tick();", 100);
}

/**轮播更新背景**/
function UpdateBackground(init, index, list, timer, playDurantTime) {
  clearTimeout(timer);
  var length = list.length;
  if (index == length) {
    index = 0;
  }
  var obj = $(list[index].item).find("foreignObject");
  var durant = list[index].durant;
  var parent = $(".body #svgcontent>g:first")[0];
  if (init) {
    $(".body #svgcontent>g:first>image").remove();
  }
  var currentElement = list[index].tagName;
  var width = programConfig.width;
  var height = programConfig.height;
  var src = list[index].src;
  var preserveAspectRatio = list[index].preserveAspectRatio;
  var background = list[index].background;
  // $("#canvas_background").attr("fill",fill);
  if (src) {
    var online_src = list[index].online_src;
    var unique = list[index].unique;
    var poster = list[index].poster;
    if (currentElement == "IMG") {//图片
      var nextElement = list[index == length - 1 ? 0 : index + 1];
      var nextSrc = "";
      if (nextElement.tagName == "IMG") {//下一张是图片
        nextSrc = nextElement.src;//下一张图片地址
        if (nextSrc) {
          var img = new Image();
          img.src = nextSrc;
          img.onload = function () {
            // console.log(nextSrc,'加载完成')
          }
        }
      }
      if ($(parent).find("img:not(.poster)").length == 0) {//第一次出现图片
        var html = `<svg viewBox="0 0 ${width} ${height}" class="img">
                <foreignObject width="${width}" height="${height}" opacity="1" blur="0">
                  <img id="bgImage" src="${src}" style="background:${background}" unique="${unique}" online_src="${online_src}" preserveAspectRatio="${preserveAspectRatio}" />
                </foreignObject>
              </svg>`;
        $(parent).append(html);
        $(".body #svgcontent>g:first>svg.img").hide();
        $("img#bgImage")[0].onload = function () {
          $(".body #svgcontent>g:first>svg.img").show();
          $(".body #svgcontent>g:first>svg.video").remove();
          if (nextSrc) {
            $(this).parent().css({
              'background-image': 'url(' + nextSrc + ')',
              "background-size": 'contain',
              "background-repeat": 'no-repeat',
              "background-position": "center"
            });
          } else {
            $(this).parent().css({ 'background-image': '' });
          }
        }
      } else {
        if (src) {
          $(parent).find("img:not(.poster)").css({ "display": "none" });
          $(parent).find("img:not(.poster)")[0].onload = function () {
            if (nextSrc) {
              $(this).parent().css({
                'background-image': 'url(' + nextSrc + ')',
                "background-size": 'contain',
                "background-repeat": 'no-repeat',
                "background-position": "center"
              });
            } else {
              $(this).parent().css({ 'background-image': '' });
            }
          }
        }
        $(parent).find("img:not(.poster)").removeAttr("src");
        $(parent).find("img:not(.poster)").attr({ "src": src, "online_src": online_src, "unique": unique }).css('background',background);
        $(parent).find("img:not(.poster)").load(function () {
          $(this).unbind("load")
          $(this).show();
        })
      }
      var video = $(parent).find("video")[0];
      if (video) {
        $(video).hide();
        video.onpause = function () {
          console.log('onpause1')
          if(STOP){
            return;
          }
          video.removeAttribute("src");
          video.load();
        }
        video.pause();
      }

    } else if (currentElement == 'VIDEO') {//视频
      var original_url = list[index].original_url;
      if ($(parent).find("video").length == 0) {//第一次出现视频
        var html = `<svg viewBox="0 0 ${width} ${height}" class="video">
                <foreignObject width="${width}" height="${height}" opacity="1" blur="0">
                  <img class="poster" src="${poster}" style="width:100%;height:100%;background:${background}" preserveAspectRatio="${preserveAspectRatio}" />
                  <video id="bgImage" width="100%" height="100%" loop="" 
                  unique="${unique}" poster="${poster}" original_url="${original_url}"
                  preserveAspectRatio="${preserveAspectRatio}"
                  style="display: none;background:${background}" online_src="${online_src}" type="video/mp4" muted="" 
                  webkit-playsinline="true"
                  playsinline="true"
                  preload="none" play_src="${src}">
                    </video>
                </foreignObject>
              </svg>`
        $(parent).append(html);
        $(".body #svgcontent>g:first>svg.video").hide();
        if (MODEL == 'PREVIEW') {
          $(".body #svgcontent>g:first>svg.video").show();
          $(".body #svgcontent>g:first>svg.img").remove();
        } else {
          $(parent).find('foreignObject .poster')[0].onload = function () {
            $(".body #svgcontent>g:first>svg.video").show();
            $(".body #svgcontent>g:first>svg.img").remove();
          }
        }
      } else {
        var play_src = src;
        if (MODEL == "PREVIEW") {
          var poster = obj.find("img.poster").attr("src");
          $(parent).find("img.poster").attr("src", poster).show();
        }
        var video = $(parent).find("video")[0];
        video.onpause = function () {
          console.log('onpause2')
          if(STOP){
            return;
          }
          video.removeAttribute("src");
          video.load();
        }
        video.pause();
        $(video).prev('.poster').attr('src', `${poster}`).css('background',background);
        $(video).attr({ "poster": `${poster}`, "play_src": play_src, "online_src": online_src, "original_url": original_url }).css('background',background);
      }
    }
  } else {//都没有的情况下
    var video = $(parent).find("video")[0];
    if (video) {
      video.pause();
    }
    $(parent).find("img,video").hide().removeAttr("src").css('background',"transparent");
    $(".body #canvas_background").attr("fill",background);
  }

  var element = "";
  if (currentElement == "IMG") {
    element = $(parent).find("img:not(.poster)")[0];
  } else if (currentElement == "VIDEO") {
    element = $(parent).find("video")[0];
  }
  if (element) {
    if (currentElement == "VIDEO") {//视频
      var src = "";
      if (MODEL == "PREVIEW") {
        var poster = list[index].original_url;
        if ($(element).prev(".poster").length == 0) {
          $(element).before(createPoster(poster));
        }
        $(element).prev(".poster").attr("src", poster);
        $(element).attr('poster', poster);
      }
      src = $(element).attr("play_src");

      $(element).attr("src", src);
      if (IS_ANDROID) {
        if (!MUTED) {//非静音
          element.removeAttribute("muted");
          element.muted = false;
        }
      }
      element.onpause = function(){//节目内视频切换清空video，节目间不清空
        $("#preview_container .content #svgcontent g:last-child foreignObject").css({"position":"","z-index":0});
        if(STOP){
          return;
        }
        console.log('onpause3')
        element.removeAttribute("src");
        element.load();
      }

      element.oncanplaythrough = function () {
        setTimeout(function () {
          if($(element).prev(".poster").is(":hidden")){//为了解决方雅设备执行两次oncanplaythrough导致视频卡顿（单个节目单个视频）
            return false;
          }
          console.log('canplaythrough');
          if(element.error != null) return;
          $("#preview_container .content #svgcontent g:last-child foreignObject").css({"position":"relative","z-index":2});
          $(element).css("display", 'block');
          $(element).prev(".poster").hide();
          var i = index;
          if (i >= length) { i = 0; }
          var nextTagName = list[i].tagName;
          if (nextTagName) {
            var nextImageSrc = "";
            if (nextTagName == 'IMG') {
              nextImageSrc = list[i].src;
            } else {
              nextImageSrc = list[i].poster;
            }
            $("#bgImage").prev(".poster").attr("src", nextImageSrc);
            $("#bgImage").attr('poster', nextImageSrc);
          }
        }, 800);
      }
      element.ontimeupdate = function(){
        if(this.currentTime >1){
          $("#preview_container .content #svgcontent g:last-child foreignObject").css({"position":""});
        }
      }
      element.onerror = function(){
        console.log("onerror: "+ element.error.code + " 视频路径：" + src);
        prompt(element);
      }
      element.play();
      if (IS_ANDROID) {
        if (INIT) {
          INIT = false;
        }
      }
    } else {//图片
      if (MODEL == "PREVIEW") {
        var src = element.getAttribute("online_src");
        if (src && src != "null") {
          element.setAttribute("src", src);
        } else {
          if (!element.getAttribute("src")) {
            element.setAttribute("src", "");
          }
        }
      } else {
        if (IS_ANDROID) {
          if (INIT) {
            INIT = false;
          }
        }
      }
    }
  }
  index++;
  var diffTimeAxis = new Date().getTime() - mainTimeAxis - playDurantTime;
  playDurantTime += (durant * 1000);

  setTimeout(function () {
    $(parent).find("video").each(function () {
      $(this).prev(".poster").show();
      this.pause();
    });
    $(parent).find(".alert_error").remove();
  }, parseInt(durant * 1000) - 200 - diffTimeAxis);
  var timer = setTimeout(function () {
    $(".body #svgcontent>g:last-child").attr('class', '');
    UpdateBackground(false, index, list, timer, playDurantTime);
  }, durant * 1000 - diffTimeAxis);
}
/**轮播更新文本框**/
function UpdateTextarea(id, index, list, timer, playDurantTime) {
  clearTimeout(timer);
  var length = list.length;
  if (index == length) {
    index = 0;
  }
  var durant = list[index].durant;
  var selected = $(".body").find("#" + id);
  var text = list[index].value;
  var fill = list[index].fill;
  var fontFamily = list[index].fontFamily;
  var fontSize = list[index].fontSize;
  var background = list[index].background;
  var fontWeight = list[index].fontWeight;
  var fontStyle = list[index].fontStyle;
  var textDecoration = list[index].textDecoration;
  var lineHeight = list[index].lineHeight;
  var color = list[index].color;
  var strokeWidth = list[index].strokeWidth;
  var strokeDasharray = list[index].strokeDasharray;
  var opacity = list[index].opacity == undefined ? 1 : list[index].opacity;
  selected.find("textarea").attr("readonly", "readonly");
  selected.attr("opacity", opacity);
  selected.removeAttr("transform")
  var transform = list[index].transform;
  if (transform && transform != "null") {
    var rotate = transform.split("rotate(")[1].split(" ")[0];
    rotate = "rotate(" + rotate + "deg)";
    if (rotate) {
      selected.find("textarea").css({ "transform": rotate});
    }
  } else {
    selected.find("textarea").css("transform", "");
  }

  // var blur = obj.attr("blur");
  // if (blur != undefined) {
  //   selected.attr("blur", blur);
  //   var filter = obj.attr("filter");
  //   if (filter && filter != "null") {
  //     if (IS_ANDROID) {
  //       var blur = selected.attr("blur");
  //       selected.find("textarea").css({ "filter": "blur(" + blur + "px)", "-webkit-filter": "blur(" + blur + "px)" });
  //     } else {
  //       selected.attr("filter", filter);
  //     }
  //   } else {
  //     if (IS_ANDROID) {
  //       selected.find("textarea").css("filter", "");
  //     } else {
  //       selected.removeAttr("filter");
  //     }
  //   }
  // } else {
  //   selected.removeAttr("blur").removeAttr("filter");
  //   selected.find("textarea").css({ "filter": "", "-webkit-filter": "" });
  // }
  selected.removeAttr("blur").removeAttr("filter");
  selected.attr({
    "fill": fill,
    "font-family": fontFamily,
    "font-size": fontSize,
    "background": background,
    "font-weight": fontWeight,
    "font-style": fontStyle,
    "text-decoration": textDecoration,
    "line-height": lineHeight,
    "color": color,
    "stroke-width": strokeWidth,
    "stroke-dasharray": strokeDasharray,

  });
  var textarea = selected.find("textarea");
  textarea.css({
    "font-size": fontSize,
    "font-family": fontFamily,
    "font-weight": fontWeight,
    "color": color,
    "background": background,
    '-webkit-text-stroke-width': strokeWidth,
    "font-style": fontStyle,
    "text-decoration": textDecoration,
  }).val(text);
  var diffTimeAxis = new Date().getTime() - mainTimeAxis - playDurantTime;
  playDurantTime += (durant * 1000);
  index++;
  timer = setTimeout(function () {
    UpdateTextarea(id, index, list, timer, playDurantTime);
  }, durant * 1000 - diffTimeAxis);
}
var aid = "";
/**轮播更新素材**/
function UpdateMaterial(id, index, list, timer, main, sync, playDurantTime) {
  currentTimeAxis = new Date().getTime();
  clearTimeout(timer);
  var currentElement = "";
  var length = list.length;
  if (index == length) {
    index = 0;
  }
  var obj = $(list[index].item).find("foreignObject");
  var durant = list[index].durant;
  var selected = $(".body").find("#" + id);
  var currentElement = list[index].tagName;
  var src = list[index].src;
  var online_src = list[index].online_src;
  var unique = list[index].unique;
  var poster = list[index].poster;
  var preserveAspectRatio = list[index].preserveAspectRatio;
  if (currentElement == 'IMG') {//图片
    if (selected.find("img:not(.poster)").length == 0) {//第一次出现图片
      var html = `<img src="${src}" unique="${unique}" preserveAspectRatio="${preserveAspectRatio}" />`;
      selected.find('svg').remove();
      selected.append(html).attr("sync", sync);
    } else {
      selected.find("img:not(.poster)").attr({ "src": src, "online_src": online_src }).show();
    }
    selected.find("img:not(.poster)").show();
    var video = selected.find("video")[0];
    if (video) {
      $(video).hide();
      video.onpause = function () {
        $(video).prev(".poster").removeAttr("src").hide();
        video.removeAttribute("src");
        video.load();
      }
      video.pause();
    }
  } else if (currentElement == 'VIDEO') {//视频
    var original_url = list[index].original_url;
    if (selected.find("video").length == 0) {//第一次出现视频
      selected.find('svg').remove();
      var html = `<img class="poster" src="${poster}" style="width:100%;height:100%;" preserveAspectRatio="${preserveAspectRatio}" />
                  <video width="100%" height="100%" loop="" src="${src}" 
                  unique="${unique}" poster="${poster}" original_url="${original_url}" 
                  preserveAspectRatio="${preserveAspectRatio}"
                  type="video/mp4" muted preload="none" style="display:none"></video>`;
      selected.append(html).attr("sync", sync);
    } else {
      selected.find("video").hide().attr({ "src": src, "online_src": online_src, "original_url": original_url, "unique": unique, "poster": `${poster}` });
      selected.find("img.poster").attr("src", original_url);
    }
    selected.find("img.poster").show();
    var img = selected.find("img:not(.poster)")[0];
    if (img) {
      $(img).hide();
    }
  } else if ($(obj).find("img:not(.poster),video").length == 0) {//都没有的情况下
    currentElement = "";
    selected.find("img,video").removeAttr("src").hide();
  }
  $(".body #svgcontent>g:last-child").attr('class', '');
  if (selected.find("img")[0]) {
    selected.find("img")[0].onload = function () {
      $(".body #svgcontent>g:last-child").attr("class", 'topZindex');
    }
  }
 
  var transform = list[index].transform;
  selected.removeAttr("transform")
  if (transform && transform != "null") {
    var rotate = transform.split("rotate(")[1].split(" ")[0];
    rotate = "rotate(" + rotate + "deg)";
    if (rotate) {
      selected.find("img,video").css({ "transform": rotate});
    }
  } else {
    selected.find("img,video").css("transform", "");
  }
  var opacity = list[index].opacity == undefined ? 1 : list[index].opacity;
  selected.attr("opacity", opacity);

  // var blur = obj.attr("blur");
  // if(blur != undefined){
  //   selected.attr("blur",blur);
  //   var filter = obj.attr("filter");
  //   console.log(CSS.supports('filter', filter))
  //   if(filter && filter != "null"){
  //     if(IS_ANDROID){
  //       var blur = selected.attr("blur");
  //       selected.find("img,video").css({"filter":"blur("+blur+"px)","-webkit-filter":"blur("+blur+"px)"});
  //     }else{
  //       selected.attr("filter",filter);
  //     }
  //   }else{
  //     if(IS_ANDROID){
  //       selected.find("img,video").css("filter","");
  //     }else{
  //       selected.removeAttr("filter");
  //     }
  //   }
  // }else{
  //   selected.removeAttr("blur").removeAttr("filter");
  //   selected.find("img,video").css({"filter":"","-webkit-filter":""});
  // }
  selected.removeAttr("blur").removeAttr("filter");

  var element = "";
  if (currentElement == "IMG") {
    element = selected.find("img:not(.poster)")[0];
  } else if (currentElement == "VIDEO") {
    element = selected.find("video")[0];
  }
  if (element) {
    if (currentElement == "VIDEO") {//视频
      if (MODEL == "PREVIEW") {
        var poster = element.getAttribute("original_url");
        if ($(element).prev(".poster").length == 0) {
          $(element).before(createPoster(poster));
        }
        $(element).prev(".poster").attr("src", poster);
        $(element).attr('poster', poster)
        var src = element.getAttribute("online_src");
        if (src && src != "null") {
          element.setAttribute("src", src);
        } else {
          if (!element.getAttribute("src")) {
            element.setAttribute("src", "");
          }
        }
      } else {
        var poster = element.getAttribute("poster");
        $(element).prev(".poster").attr("src", poster);
      }
      if (IS_ANDROID) {
        if (!MUTED) {//非静音
          element.removeAttribute("muted");
          element.muted = false;
        }
      }
      element.onpause = function () {
        console.log("素材框 paused");
      }
      function syncListener(){
        setTimeout(function () {
          if ($(element).parent().attr('tag') == 'material' && $(element).parent().attr('sync') != "false") {
            $(element).show();
            $(element).prev(".poster").hide();
            $(".body foreignObject[tag='material'][sync='true'] canvas").show();
            $(".body foreignObject[tag='material'][sync='true'] .poster").hide();

            var canvas = $(".body canvas");
            var sourceWidth = element.videoWidth;
            var sourceHeight = element.videoHeight;
            var elementWidth = sourceWidth > sourceHeight ? element.clientWidth : (sourceWidth * element.clientHeight / sourceHeight);
            var elementHeight = sourceWidth > sourceHeight ? (sourceHeight * element.clientWidth / sourceWidth) : element.clientHeight;
            Array.prototype.forEach.call(canvas, function (item) {
              preserveAspectRatio = $(item).prev().attr("preserveAspectRatio");
              if(preserveAspectRatio != "none"){//不拉申
                $(item).css({
                  "margin-top": (element.clientHeight - elementHeight) / 2 + 'px',
                  "margin-left": (element.clientWidth - elementWidth) / 2 + 'px'
                })
                item.setAttribute("width", elementWidth);
                item.setAttribute("height", elementHeight);
              }else{//拉申
                elementWidth = $(element).parent().attr("width");
                elementHeight = $(element).parent().attr("height");
                item.setAttribute("width",elementWidth);
                item.setAttribute("height", elementHeight);
              }
            });

            // 将video上的图片的每一帧以图片的形式绘制的canvas上
            var sx = 0;//可选。开始剪切的 x 坐标位置。
            var sy = 0;//可选。开始剪切的 y 坐标位置。
            var sw = sourceWidth;//可选。被剪切图像的宽度。
            var sh = sourceHeight; //可选。被剪切图像的高度。
            var dx = 0; //在画布上放置图像的 x 坐标位置。
            var dy = 0; //在画布上放置图像的 y 坐标位置。
            var dw = elementWidth;
            var dh = elementHeight;

            switchToCanvas();

            function switchToCanvas() {
              if (element.paused) {
                window.cancelAnimationFrame(aid);
                $('.body canvas').prev('.poster').remove();
                $(".body foreignObject[tag='material'][sync='true'] .alert_error").remove();
                console.log("canvas paused")
                if(!STOP){
                  $(".body canvas").remove();
                  UpdateMaterialSync(id, index, list, timer, main, sync, playDurantTime);
                }
                return;
              }

              // console.log(sx, sy, sw, sh, dx, dy, dw, dh)
              Array.prototype.forEach.call(canvas, function (item, index) {
                item.getContext("2d").clearRect(0, 0,item.width,item.height);
                item.getContext("2d").drawImage(element, sx, sy, sw, sh, dx, dy, dw, dh);
              })

              aid = window.requestAnimationFrame(switchToCanvas);
            }
          } else {
            $(element).show();
            $(element).prev(".poster").hide();
          }
        }, 800);
      }

      element.onplay = function () {//播放本地视频
        if(MODEL == 'PUBLISH'){
          console.log('onplay');
          syncListener();
        }
      }
      element.oncanplaythrough = function () {//播放在线视频
        if(MODEL == 'PREVIEW'){
          console.log('oncanplaythrough');
          syncListener();
        }
      }
      element.onerror = function(){
        console.log("onerror: "+ element.error.code + " 视频路径：" + src);
        prompt(element);
        $(".body canvas").each(function(){
          prompt(this);
        });
      }
      if (main) {
        var mainId = $(element).parent().attr('id');
        $(".body foreignObject[tag='material'][sync='true'] video").each(function () {
          if (mainId != $(this).parent().attr('id')) {
            var mainPoster = $(element).attr("poster");
            $(this).prev(".poster").attr("src",mainPoster);
            this.outerHTML = '<canvas class="canvas" tag="material" sync="true" style="display:none;transform:'+rotate+'"></canvas>';
          }
        });
        element.play();
      } else {
        if (!sync) {
          element.play();
        }
      }

    } else {//图片
      if (MODEL == "PREVIEW") {
        var online_src = element.getAttribute("online_src");
        if (online_src) {
          element.setAttribute("src", online_src);
        }
      }
    }
  } else {
    selected.find("img:not(.poster),video").hide();
    var video = selected.find("video")[0];
    if (video) {
      video.pause();
    }
  }
  index++;
  var diffTimeAxis = new Date().getTime() - mainTimeAxis - playDurantTime;
  playDurantTime += (durant * 1000);
  
  var timer = setTimeout(function () {
    if (sync) {
      if (main) {
        if (element && currentElement == "VIDEO") {
          element.pause();
        }
      } else {
        return false;
      }
    } else {
      UpdateMaterial(id, index, list, timer, false, sync, playDurantTime);
    }
    $(selected).find(".alert_error").remove();
  }, durant * 1000 - diffTimeAxis);
}
//素材框轮播控制
function UpdateMaterialSync(id, index, list, timer, main, sync, playDurantTime) {
  if (syncArray.length > 1) {
    for (var i = 0; i < syncArray.length; i++) {
      if (syncArray[i].id != id) {
        UpdateMaterial(syncArray[i].id, index, syncArray[i].elements, randomString(3), false, true, playDurantTime);
      }
    }
  }
  UpdateMaterial(id, index, list, timer, main, sync, playDurantTime)
}
/**轮播更新二维码**/
function UpdateQrCode(id, index, list, timer, playDurantTime) {
  clearTimeout(timer);
  var length = list.length;
  if (index == length) {
    index = 0;
  }
  var durant = list[index].durant;
  var selected = $(".body").find("#" + id);
  var currentElement = list[index].tagName;
  var src = list[index].src;
  var online_src = list[index].online_src;
  var unique = list[index].unique;
  var preserveAspectRatio = list[index].preserveAspectRatio;
  if (currentElement) {
    var html = `<img src="${src}" unique="${unique}" preserveAspectRatio="${preserveAspectRatio}" />`;
    selected.empty().html(html);
    var img = selected.find("img");
    if (MODEL == "PREVIEW") {
      img.attr("src", online_src);
    }
    var transform = list[index].transform;
    selected.removeAttr("transform")
    if (transform && transform != "null") {
      var rotate = transform.split("rotate(")[1].split(" ")[0];
      rotate = "rotate(" + rotate + "deg)";
      if (rotate) {
        selected.find("img").css({ "transform": rotate});
      }
    } else {
      selected.find("img").css("transform", "");
    }
    var opacity = list[index].opacity == undefined ? 1 : list[index].opacity;
    selected.attr("opacity", opacity);

    // var blur = obj.attr("blur");
    // if (blur != undefined) {
    //   selected.attr("blur", blur);
    //   var filter = obj.attr("filter");
    //   if (filter && filter != "null") {
    //     if (IS_ANDROID) {
    //       var blur = selected.attr("blur");
    //       img.css({ "filter": "blur(" + blur + "px)", "-webkit-filter": "blur(" + blur + "px)" });
    //     } else {
    //       selected.attr("filter", filter);
    //     }
    //   } else {
    //     if (IS_ANDROID) {
    //       img.css("filter", "");
    //     } else {
    //       selected.removeAttr("filter");
    //     }
    //   }
    // } else {
    //   selected.removeAttr("blur").removeAttr("filter");
    //   img.css({ "filter": "", "-webkit-filter": "" });
    // }
    selected.removeAttr("blur").removeAttr("filter");
  } else {
    selected.html(`<image style="opacity:0"></image>`);
  }
  img.css("position", "relative");
  if (list.length == 1) {//单个不轮播
    return;
  }
  index++;
  var diffTimeAxis = new Date().getTime() - mainTimeAxis - playDurantTime;
  playDurantTime += (durant * 1000);
  var timer = setTimeout(function () {
    UpdateQrCode(id, index, list, timer, playDurantTime);
  }, durant * 1000 - diffTimeAxis);

}
/**轮播更新条形码**/
function UpdateBarCode(id, index, list, timer, playDurantTime) {
  clearTimeout(timer);
  var length = list.length;
  if (index == length) {
    index = 0;
  }
  var durant = list[index].durant;
  var selected = $(".body").find("#" + id);
  var currentElement = list[index].tagName;
  var src = list[index].src;
  var online_src = list[index].online_src;
  var unique = list[index].unique;
  var preserveAspectRatio = list[index].preserveAspectRatio;
  if (currentElement) {
    var html = `<img src="${src}" unique="${unique}" preserveAspectRatio="${preserveAspectRatio}" />`;
    selected.empty().html(html);
    var img = selected.find("img");
    if (MODEL == "PREVIEW") {
      img.attr("src", online_src);
    }
    var transform = list[index].transform;
    selected.removeAttr("transform")
    if (transform && transform != "null") {
      var rotate = transform.split("rotate(")[1].split(" ")[0];
      rotate = "rotate(" + rotate + "deg)";
      if (rotate) {
        selected.find("img").css({ "transform": rotate});
      }
    } else {
      selected.find("img").css("transform", "");
    }
    var opacity = list[index].opacity == undefined ? 1 : list[index].opacity;
    selected.attr("opacity", opacity);

    // var blur = obj.attr("blur");
    // if (blur != undefined) {
    //   selected.attr("blur", blur);
    //   var filter = obj.attr("filter");
    //   if (filter && filter != "null") {
    //     if (IS_ANDROID) {
    //       var blur = selected.attr("blur");
    //       img.css({ "filter": "blur(" + blur + "px)", "-webkit-filter": "blur(" + blur + "px)" });
    //     } else {
    //       selected.attr("filter", filter);
    //     }
    //   } else {
    //     if (IS_ANDROID) {
    //       img.css("filter", "");
    //     } else {
    //       selected.removeAttr("filter");
    //     }
    //   }
    // } else {
    //   selected.removeAttr("blur").removeAttr("filter");
    //   img.css({ "filter": "", "-webkit-filter": "" });
    // }
    selected.removeAttr("blur").removeAttr("filter");
  } else {
    selected.html(`<image style="opacity:0"></image>`);
  }
  img.css("position", "relative");
  if (list.length == 1) {//单个不轮播
    return;
  }
  index++;
  var diffTimeAxis = new Date().getTime() - mainTimeAxis - playDurantTime;
  playDurantTime += (durant * 1000);
  var timer = setTimeout(function () {
    UpdateBarCode(id, index, list, timer, playDurantTime);
  }, durant * 1000 - diffTimeAxis);

}

/**更新网页**/
function UpdatePage(id, index, list, timer, playDurantTime) {
  clearTimeout(timer);
  var length = list.length;
  if (index == length) {
    index = 0;
  }
  var durant = list[index].durant;
  var src = list[index].src;
  var selected = $(".body").find("#" + id);
  var iframe = selected.find("iframe");
  if (src) {
    if (src.indexOf('http') > -1) {
      iframe[0].setAttribute("src", src);
    } else {
      iframe[0].setAttribute("src", "");
    }
    var opacity = list[index].opacity == undefined ? 1 : list[index].opacity;
    selected.attr("opacity", opacity);

    var transform = list[index].transform;
    selected.removeAttr("transform")
    if (transform && transform != "null") {
      var rotate = transform.split("rotate(")[1].split(" ")[0];
      rotate = "rotate(" + rotate + "deg)";
      if (rotate) {
        selected.find("iframe").css({ "transform": rotate});
      }
    } else {
      selected.find("iframe").css("transform", "");
    }

    // var blur = obj.attr("blur");
    // if (blur != undefined) {
    //   selected.attr("blur", blur);
    //   var filter = obj.attr("filter");
    //   if (filter && filter != "null") {
    //     if (IS_ANDROID) {
    //       var blur = selected.attr("blur");
    //       iframe.css({ "filter": "blur(" + blur + "px)", "-webkit-filter": "blur(" + blur + "px)" });
    //     } else {
    //       selected.attr("filter", filter);
    //     }
    //   } else {
    //     if (IS_ANDROID) {
    //       iframe.css("filter", "");
    //     } else {
    //       selected.removeAttr("filter");
    //     }
    //   }
    // } else {
    //   selected.removeAttr("blur").removeAttr("filter");
    //   iframe.css({ "filter": "", "-webkit-filter": "" });
    // }
    selected.removeAttr("blur").removeAttr("filter");
  } else {
    selected.attr("opacity", 0);
  }
  if (list.length == 1) {//单个不轮播
    return;
  }
  index++;
  var diffTimeAxis = new Date().getTime() - mainTimeAxis - playDurantTime;
  playDurantTime += (durant * 1000);
  var timer = setTimeout(function () {
    UpdatePage(id, index, list, timer, playDurantTime);
  }, durant * 1000 - diffTimeAxis);

}

/**更新直播**/
function UpdateLive(id, index, list, timer, playDurantTime) {
  clearTimeout(timer);
  var length = list.length;
  if (index == length) {
    index = 0;
  }
  var durant = list[index].durant;
  var src = list[index].src;
  var selected = $(".body").find("#" + id);
  var videoId = id + "_video_" + index; 
  if (src) {
    var html = `<video id="${videoId}" class="video-js vjs-default-skin vjs-big-play-centered" >
          <source src="${src}"  type="application/x-mpegURL" style="width:100%;height:100%;">
      </video>`;
      selected.empty().append(html);
      console.log(videoId);
    initLiveVideo(videoId);
    var opacity = list[index].opacity == undefined ? 1 : list[index].opacity;
    selected.attr("opacity", opacity);

    var transform = list[index].transform;
    selected.removeAttr("transform");
    if (transform && transform != "null") {
        selected.attr({ "transform": transform});
    }
    selected.removeAttr("blur").removeAttr("filter");
  } else {
    selected.attr("opacity", 0);
  }
  if (list.length == 1) {//单个不轮播
    return;
  }
  index++;
  var diffTimeAxis = new Date().getTime() - mainTimeAxis - playDurantTime;
  playDurantTime += (durant * 1000);
  
  setTimeout(function () {
    var index = 0;
    liveVideoList.map(function(item,i){
      if(item.id_ == videoId){
        var videoPlayer = liveVideoList[i];
        console.log(videoPlayer);
        videoPlayer.pause();
        videoPlayer.dispose();
        index = i;
      }
    });
    liveVideoList.splice(index,1);
  }, parseInt(durant * 1000) - 200 - diffTimeAxis);

  var timer = setTimeout(function () {
    UpdateLive(id, index, list, timer, playDurantTime);
  }, durant * 1000 - diffTimeAxis);

}

//初始化时间控件
function initTime(list) {
  var selected = $("foreignObject[tag='time']");
  if (selected.length > 0) {
    // if (IS_ANDROID) {
    //   timeElements.each(function () {
    //     var transform = $(this).parent().attr("transform");
    //     if (transform && transform != "null") {
    //       var rotate = transform.split("rotate(")[1].split(" ")[0];
    //       if (rotate) {
    //         rotate = "rotate(" + rotate + "deg)";
    //         $(this).css({ "transform": rotate, "transform-origin": "center" });
    //       }
    //     }
    //     var opacity = $(this).parent().attr("opacity") == undefined ? 1 : $(this).parent().attr("opacity");
    //     $(this).css("opacity", opacity);
    //   })
    // }
    // console.log(list)
    // return;
    var index = 0;
    var fill = list[index].fill;
    var fontFamily = list[index].fontFamily;
    var fontSize = list[index].fontSize;
    var background = list[index].background;
    var fontWeight = list[index].fontWeight;
    var fontStyle = list[index].fontStyle;
    var textDecoration = list[index].textDecoration;
    var lineHeight = list[index].lineHeight;
    var color = list[index].color;
    var strokeWidth = list[index].strokeWidth;
    var strokeDasharray = list[index].strokeDasharray;
    var opacity = list[index].opacity == undefined ? 1 : list[index].opacity;
    selected.attr("opacity", opacity);
    selected.removeAttr("transform")
    var transform = list[index].transform;
    if (transform && transform != "null") {
      var rotate = transform.split("rotate(")[1].split(" ")[0];
      rotate = "rotate(" + rotate + "deg)";
      if (rotate) {
        selected.find("textarea").css({ "transform": rotate});
      }
    } else {
      selected.find("textarea").css("transform", "");
    }
    selected.removeAttr("blur").removeAttr("filter");
    selected.attr({
      "fill": fill,
      "font-family": fontFamily,
      "font-size": fontSize,
      "background": background,
      "font-weight": fontWeight,
      "font-style": fontStyle,
      "text-decoration": textDecoration,
      "line-height": lineHeight,
      "color": color,
      "stroke-width": strokeWidth,
      "stroke-dasharray": strokeDasharray,

    });
    var div = selected.find(".time");
    div.css({
      "font-size": fontSize,
      "font-family": fontFamily,
      "font-weight": fontWeight,
      "color": color,
      "background": background,
      '-webkit-text-stroke-width': strokeWidth,
      "font-style": fontStyle,
      "text-decoration": textDecoration,
      "z-index":9,
    });
    tick();
  }
}
var syncArray = new Array;
var mainTimeAxis = 0;
/**预览设置轮播**/
function initPreviewList(str) {
  MODEL = str;
  mainTimeAxis = new Date().getTime();
  programConfig.elements.map(item => {
    var tag = item.tag;
    var list = item.elements.filter((item)=>{if(item.online){return item}});
    // var list = item.elements.filter((item)=>{if(item.online){ if(str == "PUBLISH" && IS_ANDROID){ if(item.src){item.src = '../../material/'+item.src;item.poster = '../../material/'+item.poster }  }return item}});
    var id = item.id;
    var online = item.online;
    if (list.length == 0 || !online) {
      $("#" + id).remove();
      return;
    }
    switch (tag) {
      case 'background':
        UpdateBackground(true, 0, list, randomString(3), 0);
        break;
      case 'textarea':
        UpdateTextarea(id, 0, list, randomString(3), 0);
        break;
      case 'material':
        var sync = item.sync;
        if (sync) {
          syncArray.push(item);
        } else {
          UpdateMaterial(id, 0, list, randomString(3), false, sync, 0);
        }
        break;
      case 'qrcode':
        UpdateQrCode(id, 0, list, randomString(3), 0);
        break;
      case 'barcode':
        UpdateBarCode(id, 0, list, randomString(3), 0);
        break;
      case 'webpage':
        UpdatePage(id, 0, list, randomString(3), 0);
        break;
      case 'live':
        UpdateLive(id, 0, list, randomString(3), 0);
          break;
      case 'time':
        initTime(list);
        break;
      default:
        break;
    }
  });
  if (syncArray.length > 0) {
    var array = syncArray[syncArray.length - 1];
    var id = array.id;
    var list = array.elements;
    list.map(item => { item.id = id; item.sync = array.sync; });
    UpdateMaterialSync(id, 0, list, randomString(3), true, true, 0);
  }
}

/**直播控件初始化 */
var liveVideoList = [];
function initLiveVideo(videoId){
  var myPlayer = videojs(videoId,{
    poster:'../images/loading.gif',
    bigPlayButton : false,
    textTrackDisplay : false,
    posterImage: true,
    errorDisplay : false,
    controlBar : false
  },function(){
      this.on('loadedmetadata',function(){
          // console.log('loadedmetadata');
      })
      this.on('ended',function(){
          // console.log('ended')
      })
      this.on('firstplay',function(){
          // console.log('firstplay')
      })
      this.on('loadstart',function(){
          // console.log('loadstart')
          document.getElementById(videoId).style.width = "100%";
	        document.getElementById(videoId).style.height = "100%";
      })
      this.on('loadeddata',function(){
          // console.log('loadeddata');
          this.play();
      })
      this.on('seeking',function(){
          // console.log('seeking')
      })
      this.on('seeked',function(){
          // console.log('seeked')
      })
      this.on('waiting',function(){
          // console.log('waiting')
      })
      this.on('pause',function(){
          // console.log('pause')
      })
      this.on('play',function(){
          // console.log('play')
      })
  });
  liveVideoList.push(myPlayer);
}

/**下发后修改画布尺寸**/
function setSize() {
  var width = programConfig.width;
  var height = programConfig.height;
  var deviceWidth = window.screen.width;
  var deviceHeight = window.screen.height;
  var zoom = 1;
  if((width == 3840 && height == 2160 && deviceWidth == 1920 && deviceHeight == 1080) 
    || (width == 2160 && height == 3840 && deviceWidth == 1080 && deviceHeight == 1920)){ //4k 横屏或竖屏
    if(width>height){
      zoom = deviceWidth/width;
    }else{
      zoom = deviceHeight/height;
    }
  }
  $(".body")[0].style.zoom = zoom;
  $("#svgcontent").attr({ "width": width, "height": height, "x": 0, "y": 0 }).removeAttr("viewBox");
  document.getElementById("svgcontent").setAttribute("viewBox","0 0 " + width + " " + height);
}

function previewClose() {
  $(".ant-modal-close").click(function () {
    var id = window.setTimeout(function () { }, 0);
    while (id--) { window.clearTimeout(id); }//停止计数器
    syncArray = [];
    mainTimeAxis = 0;
    $(".body").empty();
    if ($("#preview_container").length > 0) {
      $("#preview_container").hide();
    }
    console.log(liveVideoList.length);
    liveVideoList.map(function(videoPlayer){
      console.log(videoPlayer);
      videoPlayer.pause();
      videoPlayer.dispose();
    });
    liveVideoList = [];
  });
}

function nameFormat(str, unique) {
  const fileName = str.lastIndexOf(".");//获取到文件名开始到最后一个“.”的长度。
  const fileNameLength = str.length;//获取到文件名长度
  const fileFormat = str.substring(fileName + 1, fileNameLength);//截取后缀名
  return unique + '.' + fileFormat;
}

function createPoster(poster) {
  return `<image class="poster" src=${poster} style="width:100%;height:100%;">`;
}

function initIMage() {
  if (document.addEventListener) {
    document.addEventListener('webkitvisibilitychange', function () {
      // console.log(document.webkitVisibilityState);
      if (document.webkitVisibilityState == "visible") {
        // console.log("游览器处于最大化",new Date().getTime());
        location.reload();
      } else {
        // console.log("游览器处于最小化");

      }
    })
  }
  pageMuted();
  if (IS_ANDROID) {
    $("body image").each(function () {
      var unique = this.getAttribute("unique");
      var src = this.getAttribute("xlink:href");
      var name = nameFormat(src, unique);
      this.setAttribute("src", name);
    });
  }
  var head = document.head || document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = "text/javascript";
  script.setAttribute("src",'./program.json');
  head.appendChild(script);
  script.onload = function(){
    setSize();
    initPreviewList('PUBLISH');
  };
  script.onerror =function(){
    $(".body").html("<div class='error'>缺少节目配置文件</div>")
  };
}

function videoResume() {
  console.log("videoResume")
  STOP = false;
  $("video").each(function () {
    this.play();
  })
}

function videoPause() {
  console.log("videoPause")
  STOP = true;
  $("video").each(function () {
    this.pause();
  })
}

function pageStop() {
  console.log("pageStop调用")
  STOP = true;//android调用
  var id = window.setTimeout(function () { }, 0);
  while (id--) { window.clearTimeout(id); }//停止计数器
  $("video").each(function () {
    this.pause();
  })
}

function pageDestroy() {
  $("video").each(function () {
    this.pause();
    $(this).prev(".poster").show();
    this.removeAttribute("src");
    this.load();
    delete this;
    $(this).remove();
  });
}

function pageMuted() {
  if (IS_ANDROID && typeof (pageLoad.IsMuted) === 'function') {
    MUTED = pageLoad.IsMuted();
  }
}

function prompt(element){
  $('<div class="alert_error">')
      .appendTo($(element).parent())
      .css({"display":"flex",
      "align-items":"center",
      "justify-content":"center",
      "z-index":99999,
      "left":"0",
      "top":"0",
      "width": "100%",
      "height":"100%",
      "position": "absolute",
      "font-size": "2vw",
      "font-weight":"bold",
      "background-color": "rgba(0,0,0,.45)",
      "color":"#ffe58f"
    })
    .html('视频播放出错 '+element.error.code)
    .show();
      // .delay(10000)
      // .fadeOut(10,function(){
      //     $('.promptModal').remove();
      // });
};